1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.cache;
18
19 import com.google.caliper.AfterExperiment;
20 import com.google.caliper.BeforeExperiment;
21 import com.google.caliper.Benchmark;
22 import com.google.caliper.Param;
23 import com.google.common.primitives.Ints;
24
25 import java.util.Random;
26 import java.util.concurrent.atomic.AtomicLong;
27
28
29
30
31
32
33 public class LoadingCacheSingleThreadBenchmark {
34 @Param({"1000", "2000"}) int maximumSize;
35 @Param("5000") int distinctKeys;
36 @Param("4") int segments;
37
38
39
40 @Param("2.5") double concentration;
41
42 Random random = new Random();
43
44 LoadingCache<Integer, Integer> cache;
45
46 int max;
47
48 static AtomicLong requests = new AtomicLong(0);
49 static AtomicLong misses = new AtomicLong(0);
50
51 @BeforeExperiment void setUp() {
52
53
54 max = Ints.checkedCast((long) Math.pow(distinctKeys, concentration));
55
56 cache = CacheBuilder.newBuilder()
57 .concurrencyLevel(segments)
58 .maximumSize(maximumSize)
59 .build(
60 new CacheLoader<Integer, Integer>() {
61 @Override public Integer load(Integer from) {
62 return (int) misses.incrementAndGet();
63 }
64 });
65
66
67
68
69
70 while (cache.getUnchecked(nextRandomKey()) < maximumSize) {}
71
72 requests.set(0);
73 misses.set(0);
74 }
75
76 @Benchmark int time(int reps) {
77 int dummy = 0;
78 for (int i = 0; i < reps; i++) {
79 dummy += cache.getUnchecked(nextRandomKey());
80 }
81 requests.addAndGet(reps);
82 return dummy;
83 }
84
85 private int nextRandomKey() {
86 int a = random.nextInt(max);
87
88
89
90
91
92
93
94 return (int) Math.pow(a, 1.0 / concentration);
95 }
96
97 @AfterExperiment void tearDown() {
98 double req = requests.get();
99 double hit = req - misses.get();
100
101
102 System.out.println("hit rate: " + hit / req);
103 }
104
105
106
107
108 }